#/usr/bin/env python

import sys
import re, os, html2text
from docx import Document

name_mapping = []

target = None
with open("names.md") as f:
    for l in f:
        l = l.strip()
        if len(l) < 3:
            continue
        if l[:3] == "## ":
            target = l[2:]
        elif l[0] == "-":
            source = l[1:].strip()[1:-1]
            if source and target:
                name_mapping.append((source.strip(), target.strip()))

def convert(fn):
    with open(fn) as f:
        cid = "".join(re.findall("\d", fn))
        texts = html2text.html2text(f.read())
        for t in re.finditer("\d+\/4\d+", texts):
            if t.group()[0] == "0":
                continue
            texts = texts[t.end():]
            break
        for t in re.finditer("\[\次へ \>\>\]|\[\<\< 前へ\]", texts):
            texts = texts[:t.start()]
            break
        texts = texts.strip()
        for mapping in name_mapping:
            texts = re.sub(mapping[0], mapping[1], texts)
        with open(f"text/{cid}.txt", "w") as txtf:
            txtf.write(texts)

all_texts = []

if len(sys.argv) < 2:
    start_n = 0
else:
    start_n = int(sys.argv[1])

for i in range(start_n, 1000):
    fn = f"html/{i}.html"
    if not os.path.exists(fn):
        continue
    print(fn)
    convert(fn)
    document = Document()
    with open(f"text/{i}.txt") as f:
        texts = f.read()
        all_texts.append(texts)
        document.add_paragraph(texts)
        document.add_page_break()
    document.save(f'docx/{i}.docx')

with open("all.txt", "w") as f:
    f.write("\n\n\n\n\n".join(all_texts))
